package com.dhecp.project.system.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.config.Global;
import com.dhecp.common.constant.Constants;
//import com.dhecp.common.config.ServerConfig;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.common.utils.file.FileUploadUtils;
import com.dhecp.common.utils.file.FileUtils;
import com.dhecp.core.utils.FastDFSUtil;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.service.ButtonStateService;
import com.dhecp.project.finance.domain.OperateServiceChargeApply;
import com.dhecp.project.finance.service.OperateServiceChargeApplyService;
import com.dhecp.project.system.domain.SysFilesInfo;
import com.dhecp.project.system.service.SysFilesInfoService;

/**
 * 文件上传下载Controller
 * 
 * @author kimiloo
 * @date 2020-02-15
 */
@Controller
@RequestMapping("/system/fileinfo")
public class SysFilesInfoController extends BaseController {
	private String prefix = "system/fileinfo";

	@Autowired
	private SysFilesInfoService sysFilesInfoService;
//	@Autowired
//    private ServerConfig serverConfig;
	@Autowired
	private ButtonStateService buttonStateService;
    @Autowired
    private OperateServiceChargeApplyService operateServiceChargeApplyService;

	@RequiresPermissions("system:fileinfo:view")
	@GetMapping()
	public ModelAndView fileinfo(ModelMap mmap) {
        ModelAndView modelAndView = this.getModelAndView();
	    String uploadUrl = FileUploadUtils.getUploadUrl();
        modelAndView.addObject("uploadUrl", uploadUrl);
        modelAndView.addObject("createUser", ShiroUtils.getMandatorId());
        modelAndView.setViewName(prefix + "/fileinfo");
        return modelAndView;
	}

	/**
     * 打开列表页
     * @param 对应实体类的json格式字符串
     * @return ModelAndView
     * @author kimiloo
	 * @throws Exception 
     */
   //@RequiresPermissions("system:fileinfo:view")
    @GetMapping("/add")
    public ModelAndView listView(@RequestParam Map<String, Object> params) throws Exception{
        ModelAndView mv = this.getModelAndView();
        Map<String, Object> buttonState = new HashMap<String, Object>();	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
        Map<String, Object> paramsButton = new HashMap<String, Object>();
        
        String moduleTable = params.get("moduleTable").toString();
        paramsButton.put("moduleTable", params.get("moduleTable").toString());
        AjaxResult ajaxResult = new AjaxResult();

        try{
        	buttonState = buttonStateService.getButtonStateObjectForUser(paramsButton);	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
        	buttonState.put("showAdd", true);
        	buttonState.put("showDelete", true);
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        
        boolean ableEdit = true;
        if ("TCW_OPERATESERVICECHARGEAPPLY".equals(moduleTable)) {
			String guid = params.get("fileMark").toString();
			OperateServiceChargeApply operateServiceChargeApply = operateServiceChargeApplyService.queryOperateServiceChargeApplyByGuid(guid);
			if (operateServiceChargeApply.getEffectStock() == true) {
				ableEdit = false;
			}
		}
        if ("TP_FBABOXS".equals(moduleTable)) {
            ableEdit = false;
        }
        String uploadUrl = FileUploadUtils.getUploadUrl();
        String fileViewUrl = FileUploadUtils.getFileViewUrl();
        mv.addObject("uploadUrl", uploadUrl);
        mv.addObject("fileViewUrl", fileViewUrl);
        mv.addObject("createUser", ShiroUtils.getMandatorId());
        mv.addObject("maxFileSize",Global.getConfig("spring.servlet.multipart.max-file-size"));	//服务器上传文件最大值
        mv.addObject("buttonState", TypeUtils.mapToJson(buttonState));	//按钮状态：（可用：enable，禁用：disable，隐藏：hidden）
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("fileMark", params.get("fileMark"));
        mv.addObject("fieldName", params.get("fieldName"));
        mv.addObject("moduleFile", params.get("moduleFile"));
        mv.addObject("moduleTable", params.get("moduleTable"));
        mv.addObject("vType", params.get("vType"));
        mv.addObject("ableEdit", ableEdit);
        mv.setViewName(prefix + "/list");
        return mv;
    }

	/**
     * 输出附件配置
     * @param 对应实体类的json格式字符串
     * @return ModelAndView
     * @author kimiloo
	 * @throws Exception
     */
   //@RequiresPermissions("system:fileinfo:view")
    @GetMapping("/selectFileSystem")
    @ResponseBody
    public AjaxResult selectFileSystem(@RequestParam Map<String, Object> params) throws Exception{
        String uploadUrl = FileUploadUtils.getUploadUrl();
        params.put("uploadUrl",uploadUrl);
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(params).toString());
    }

    
    /**
     * 文件列表
     * @param  对应实体类的json格式字符串
     * @return ModelAndView
     * @author kimiloo
     */
//    @RequiresPermissions("system:fileinfo:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo fileListJson(@RequestParam Map<String, Object> params){
		List<SysFilesInfo> list = new ArrayList<SysFilesInfo>();
		if (params.get("fileMark") == null || params.get("fileMark") == ""){params.put("fileMark", "NoFileMark");}
		try{
			list = sysFilesInfoService.queryList(params);
		}catch(Exception e){
			return getDataTable(this.getExceptionMessage(e).toString());
		}
        return getDataTable(list);
    }
    
//    /**
//     * 上传文件
//     * @param  对应实体类的json格式字符串
//     * @return AjaxResult
//     * @author kimiloo
//     */
//	@PostMapping("/upload")
//	@ResponseBody
//	public AjaxResult uploadFile(@RequestParam("file") MultipartFile uploadfile, @RequestParam Map<String, Object> params) throws Exception{
//        // 上传文件路径
//        String fileDirPath = Global.getUploadPath();
//        fileDirPath = Global.getProfile() + "/" + params.get("moduleFile");
//
//        AjaxResult ajaxResult = new AjaxResult();
//        String filePath = "";
//        String uploadType = Global.getUploadType().toLowerCase();
//        //根据不同上传类型调用相应方法
//        if(uploadType.contains(Constants.UPLOAD_FASTDFS)){//当为fastdfs
//            filePath = FastDFSUtil.upload(uploadfile);  //上传并返回新文件名称
//        }else{
//            filePath = FileUploadUtils.upload(fileDirPath, uploadfile);  //上传并返回新文件名称
//        }
//        String fileName = uploadfile.getOriginalFilename();
//        String fileExt = FileUploadUtils.getExtension(uploadfile);
//        long fileSize = uploadfile.getSize();
//        //String fileUrl = serverConfig.getUrl() + filePath;		//文件url
//        String fileSizeStr = "";
//        String fileSizeUnit = "";
//        Map<String, Object> mapObj = FileUploadUtils.convertFileSize(uploadfile.getSize());
//        if(mapObj != null && mapObj.containsKey("fileSize")){
//            fileSizeStr = mapObj.get("fileSize").toString();
//        }
//        if(mapObj != null && mapObj.containsKey("fileSizeUnit")){
//            fileSizeUnit = mapObj.get("fileSizeUnit").toString();
//        }
//        params.put("fileSize", fileSizeStr);
//        params.put("fileSizeUnit", fileSizeUnit);
//        params.put("fileName", StringUtils.getFileNameNoEx(fileName));
//        params.put("fileType", fileExt);
//        params.put("filePath", filePath);
//        try {
//        	ajaxResult= sysFilesInfoService.insertSysFilesInfo(params);
//        }catch (Exception e) {
//        	ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
//        }
//        return ajaxResult;
//    }
    
    /**
     * 添加文件信息到数据库
     * @param  对应实体类的json格式字符串
     * @return AjaxResult
     * @author kimiloo
     */
	@PostMapping("/addFilesInfo")
	@ResponseBody
	public AjaxResult addFilesInfo(@RequestParam Map<String, Object> params) throws Exception{

        AjaxResult ajaxResult = new AjaxResult();
        params.put("createUser", ShiroUtils.getUserId());
    	ajaxResult= sysFilesInfoService.insertSysFilesInfo(params);
        return ajaxResult;
    }

    /**
     * 上传邮件图片文件
     * @param jsonParam 这个是阿里的 fastjson对象
     * @return
     */
    @PostMapping("/uploadmailimg")
    @ResponseBody
    public String uploadMailImg(@RequestParam("file") MultipartFile uploadfile, @RequestParam Map<String, Object> params) throws Exception{
        // 上传文件路径
        String fileDirPath = Global.getUploadPath();
        fileDirPath = Global.getProfile() + "/" + params.get("moduleFile");

        AjaxResult ajaxResult = new AjaxResult();
        String filePath = "";
        String uploadType = Global.getUploadType().toLowerCase();
        //根据不同上传类型调用相应方法
        if(uploadType.contains(Constants.UPLOAD_FASTDFS)){//当为fastdfs
            filePath = FastDFSUtil.upload(uploadfile);  //上传并返回新文件名称
        }else{
            filePath = FileUploadUtils.upload(fileDirPath, uploadfile);  //上传并返回新文件名称
        }
        String fileName = uploadfile.getOriginalFilename();
        String fileExt = FileUploadUtils.getExtension(uploadfile);
        String fileSizeStr = "";
        String fileSizeUnit = "";
        Map<String, Object> mapObj = FileUploadUtils.convertFileSize(uploadfile.getSize());
        if(mapObj != null && mapObj.containsKey("fileSize")){
            fileSizeStr = mapObj.get("fileSize").toString();
        }
        if(mapObj != null && mapObj.containsKey("fileSizeUnit")){
            fileSizeUnit = mapObj.get("fileSizeUnit").toString();
        }
        params.put("fileSize", fileSizeStr);
        params.put("fileSizeUnit", fileSizeUnit);
        params.put("fileName", StringUtils.getFileNameNoEx(fileName));
        params.put("fileType", fileExt);
        params.put("filePath", filePath);
        params.put("createUser", ShiroUtils.getMandatorId());
        try {
            ajaxResult= sysFilesInfoService.insertSysFilesInfo(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        JSONObject result = new JSONObject();
        if(ajaxResult.get("code").equals(0)){
            ArrayList<String> list = new ArrayList<String>();
            list.add(filePath);
            result.put("errno", 0);
            result.put("data", list);
        }else{
            result.put("errno", 1);
        }

        return result.toJSONString();
    }

	/**
     * 下载文件
     * 
     * @param guid 文件guid
     * @return response
     * @author kimiloo
     */
    @GetMapping("download")
    public void fileDownload(String guid, HttpServletResponse response, HttpServletRequest request){
        try
        {
        	SysFilesInfo sysFile = sysFilesInfoService.selectSysFilesInfoById(guid);
            String realFileName = sysFile.getFileName() + "." + sysFile.getFileType();
//          String filePath = request.getServerName() + sysFile.getFilePath();  		//链接地址
            String filePath = Global.getProfile() + StringUtils.substringAfter(sysFile.getFilePath(), Constants.RESOURCE_PREFIX);//sysFile.getFilePath().replace("/profile", "");
            long fileLength = new File(filePath).length();
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
			response.setHeader("Content-Length", String.valueOf(fileLength));
            String uploadType = Global.getUploadType().toLowerCase();
            if(uploadType.contains(Constants.UPLOAD_FASTDFS)){//当为fastdfs
                FastDFSUtil.download(sysFile.getFilePath(), response.getOutputStream());
            }else{
                FileUtils.writeBytes(filePath, response.getOutputStream());
            }
        }
        catch (Exception e)
        {
            //log.error("下载文件失败", e);
        }
    }

	/**
	 * 删除文件
	 * @param infoItems 必要参数：档案信息主表，对应实体类的json格式字符串
	 */
//	@RequiresPermissions("system:fileinfo:delete")
	@PostMapping("/delete")
	@ResponseBody
    @RepeatSubmit
	public AjaxResult fileDelete(@RequestParam Map<String, Object> params) {
		AjaxResult ajaxResult = new AjaxResult();
        try {
            //ajaxResult= sysFilesInfoService.deleteSysFilesInfoById(params);
            List<SysFilesInfo> filesList = JSON.parseArray(params.get("infoItems").toString(), SysFilesInfo.class);
            if (filesList == null || filesList.size() == 0) {
                return AjaxResult.error(MessageUtils.message("upload.delete.error"));
            }
            List<String> ids = new ArrayList<String>();
    		for (SysFilesInfo sysFilesInfo : filesList){
    			ids.add(sysFilesInfo.getGuid());
    		}
            int days = 180;
    		List<SysFilesInfo> unfilesList = sysFilesInfoService.overDateList(ids,days);
    		if (unfilesList.size() > 0) {
    			String resMsg = "附件 ";
    			for (SysFilesInfo unsysFilesInfo : unfilesList){
    				resMsg += "'"+unsysFilesInfo.getFileName()+"' ";
    			}
    			resMsg += "上传超过 "+days+" 天，只有管理员才能操作删除";
                return AjaxResult.error(resMsg);
            }

            for (SysFilesInfo sysFilesInfo : filesList){
                String guid = sysFilesInfo.getGuid();
                String filePath = Global.getProfile() + StringUtils.substringAfter(sysFilesInfo.getFilePath(), Constants.RESOURCE_PREFIX);//sysFilesInfo.getFilePath().replace("/profile", "");
                sysFilesInfoService.deleteSysFilesInfoByIds(guid);
                String uploadType = Global.getUploadType().toLowerCase();
                if(uploadType.contains(Constants.UPLOAD_FASTDFS)){//当为fastdfs
                    FastDFSUtil.delete(filePath);
                }else {
                    FileUtils.deleteFile(filePath);        //删除文件
                }
            }
            ajaxResult = AjaxResult.success(MessageUtils.message("module.success.issuccess"));
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e)); 
        }
        return ajaxResult;
	}

    /**
     * 修改是否隐藏字段——数据提交
     * @param infoItems 必要参数：对应实体类的json格式字符串，包含（guid,bHidden）
     * @return AjaxResult
     * @author DH-Xxj
     */
//    @RequiresPermissions("system:fileinfo:edit")
    @Log(title = "修改是否隐藏", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult bHiddenEditPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("infoItems") == null || params.get("infoItems") == ""){
        	return AjaxResult.error("缺少参数infoItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= sysFilesInfoService.updateBHidden(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
}
